<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="1024" @ok="handleSubmit">
    <BasicForm @register="registerForm" ref="formRef" :disabled="true">
      <template #workingCalendarSlot="{ model, field }">
        <a-input-search v-model:value="model[field]" placeholder="请选择工作日历" readonly :disabled="isDetail" @search="workHandleView" />
      </template>
      <template #processNameSlot="{ model, field }">
        <a-input-search v-model:value="model[field]" placeholder="请选择加工工艺" readonly :disabled="isDetail" @search="processManagementOpen" />
      </template>
    </BasicForm>
    <!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated @change="handleChangeTabs">
      <a-tab-pane tab="加工工序" key="psWorkCenterItem" :forceRender="true">
        <JVxeTable keepSource resizable ref="psWorkCenterItem" :loading="psWorkCenterItemTable.loading"
          :columns="psWorkCenterItemTable.columns" :dataSource="psWorkCenterItemTable.dataSource" :height="340"
          :rowNumber="true" :rowSelection="true" :disabled="formDisabled" @valueChange="onValueChange" :toolbar="true">
          <template #processCodeSlot="props">
            <a-input-search @search="handleProcessCodeView(props.row)" placeholder="请选择工艺" readonly :disabled="isDetail" v-model:value="props.row.processCode"></a-input-search>
          </template>
        </JVxeTable>
      </a-tab-pane>
    </a-tabs>

  </BasicModal>
  <!-- 供应商 -->
  <workingCalendarSelectModel @register="workingRegModal" @getSelectResult="workingHandleSuccess" v-bind="getBindValue">
  </workingCalendarSelectModel>
  <!-- 加工工艺 -->
  <ProcessModal @register="processRegister" @getSelectResult="handleProcesshanged" />
  <ProcessModal @register="processRegister2" @getSelectResult="handleProcesshanged2" />
</template>

<script lang="ts" setup>
import { ref, computed, unref, reactive, watch } from 'vue';
import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { JVxeTable } from '/@/components/jeecg/JVxeTable';
import { useJvxeMethod } from '/@/hooks/system/useJvxeMethods.ts';
import { formSchema, psWorkCenterItemColumns } from '../PsWorkCenter.data';
import { saveOrUpdate, psWorkCenterItemList } from '../PsWorkCenter.api';
import { VALIDATE_FAILED } from '/@/utils/common/vxeUtils';
import workingCalendarSelectModel from '/@/views/components/workingCalendarSelectModel.vue';
import ProcessModal from '/@/views/components/processManagementSelectModels.vue';

// Emits声明
const emit = defineEmits(['register', 'success']);
const isUpdate = ref(true);
const isDetail = ref(false);
const formDisabled = ref(false);
const refKeys = ref(['psWorkCenterItem']);
const activeKey = ref('psWorkCenterItem');
const psWorkCenterItem = ref();
const tableRefs = { psWorkCenterItem };
const psWorkCenterItemTable = reactive({
  loading: false,
  dataSource: [],
  columns: psWorkCenterItemColumns,
});
//表单配置
const [registerForm, { setProps, resetFields, setFieldsValue, validate }] = useForm({
  labelWidth: 100,
  schemas: formSchema,
  disabled:true,
  showActionButtonGroup: false,
  baseColProps: { span: 8 },
});
watch(
  () => psWorkCenterItemTable.dataSource,
  (newValue, oldValue) => {
    // console.log("旧数据",oldValue)
    // console.log("新数据",newValue)
  }
);
const operatFormItem = ref<any>(null)
const [processRegister2, { openModal: openProcessModal }] = useModal();
//表单赋值
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  //重置表单
  await reset();
  setModalProps({ confirmLoading: false, showCancelBtn: data?.showFooter, showOkBtn: data?.showFooter });
  isUpdate.value = !!data?.isUpdate;
  isDetail.value = !!data?.isDetail;
  formDisabled.value = !data?.showFooter;
  title.value = data.title
  if (unref(isUpdate)) {
    //表单赋值
    await setFieldsValue({
      ...data.record,
    });
    requestSubTableData(psWorkCenterItemList, { id: data?.record?.id }, psWorkCenterItemTable);
  }
  // 隐藏底部时禁用整个表单
  setProps({ disabled: !data?.showFooter});
});
//方法配置
const [handleChangeTabs, handleSubmit, requestSubTableData, formRef] = useJvxeMethod(
  requestAddOrEdit,
  classifyIntoFormData,
  tableRefs,
  activeKey,
  refKeys
);

//设置标题
const title = computed(() => ( unref(isDetail) ? '详情' : !unref(isUpdate) ? '新增' : '编辑'));
async function reset() {
  await resetFields();
  activeKey.value = 'psWorkCenterItem';
  psWorkCenterItemTable.dataSource = [];
}
function classifyIntoFormData(allValues) {
  let main = Object.assign({}, allValues.formValue);
  return {
    ...main, // 展开
    psWorkCenterItemList: allValues.tablesValue[0].tableData,
  };
}
//表单提交事件
async function requestAddOrEdit(values) {
  try {
    values.isProductionLine= values.isProductionLine&& values.isProductionLine== true ? 1 : 0;
    setModalProps({ confirmLoading: true });
    //提交表单
    await saveOrUpdate(values, isUpdate.value);
    //关闭弹窗
    closeModal();
    //刷新列表
    emit('success');
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
const [workingRegModal, { openModal: openWorkingModal }] = useModal();
const [processRegister, { openModal: openProcessManagementModal }] = useModal();
const getBindValue = Object.assign({}, '');

// 值改变时触发的事件  获取到当前行的索引
function onValueChange( {row, rowIndex}) {
  // 处理行号
  row.rowNum = (rowIndex + 1) * 10;
}
function handleProcesshanged2(value, _options) {
  if (operatFormItem.value) {
    operatFormItem.value.processCode = value[0].item.processCoding
    operatFormItem.value.processName = value[0].item.processName
    operatFormItem.value.processId = value[0].item.id
  }
}
function handleProcessCodeView(row: any) {
  operatFormItem.value = row
  openProcessModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
//打开选择工作日历
function workHandleView(props) {
  openWorkingModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
//分组选择回写
function workingHandleSuccess(val, values) {
  setFieldsValue({
    workingCalendarName: val[0].label,
    workCalendarId: val[0].value,
  });
}
//打开加工工艺
function processManagementOpen() {
  openProcessManagementModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}

// 加工工艺回写
function handleProcesshanged(val) {
  setFieldsValue({
    processManagementId: val[0].value,
    processManagementName: val[0].label,
  });
}

</script>

<style lang="less" scoped>
/** 时间和数字输入框样式 */
:deep(.ant-input-number) {
  width: 100%;
}

:deep(.ant-calendar-picker) {
  width: 100%;
}
</style>
